interface FormatOptions {
  decimalPlaces?: number;
  spaceBetween?: boolean;
  uppercase?: boolean;
  units?: string[];
}

export function formatLargeNumber(
  num: number,
  options: FormatOptions = {}
): string {
  const {
    decimalPlaces = 1,
    spaceBetween = false,
    uppercase = false,
    units = ['', '万', '億', '兆'],
  } = options;

  if (num === 0) return '0';

  const absNum = Math.abs(num);
  const sign = num < 0 ? '-' : '';

  if (absNum < 1) {
    return num.toString();
  }

  const unitIndex = Math.min(
    Math.floor(Math.log10(absNum) / 4),
    units.length - 1
  );

  if (unitIndex === 0) {
    return num.toString();
  }

  const scaledValue = absNum / Math.pow(10000, unitIndex);
  const baseUnit = units[unitIndex] ?? '';
  const unit = uppercase ? baseUnit.toUpperCase() : baseUnit;
  const space = spaceBetween ? ' ' : '';

  if (Math.abs(scaledValue - Math.round(scaledValue)) < 1e-10) {
    return `${sign}${Math.round(scaledValue)}${space}${unit}`;
  }

  return `${sign}${scaledValue.toFixed(decimalPlaces)}${space}${unit}`;
}
